import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 单视频播放页面
/// 显示单个视频的播放界面，包括视频播放器、视频信息、互动功能等
class VideoPlayerPage extends StatefulWidget {
  final PostModel post;
  final String videoUrl;
  final String? videoTitle;

  const VideoPlayerPage({
    super.key,
    required this.post,
    required this.videoUrl,
    this.videoTitle,
  });

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  VideoPlayerController? _controller;
  bool _isInitialized = false;
  bool _isLoading = true;
  bool _hasError = false;
  String? _errorMessage;
  bool _showControls = true;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
    _startAutoHideControls();
  }

  /// 初始化视频播放器
  Future<void> _initializeVideo() async {
    try {
      Logger.d('VIDEO_PLAYER', '初始化视频播放器 - URL: ${widget.videoUrl}');
      Logger.d('VIDEO_PLAYER', '视频URL类型: ${widget.videoUrl.runtimeType}');

      // 验证URL格式
      if (widget.videoUrl.isEmpty) {
        throw Exception('视频URL为空');
      }

      final videoUri = Uri.parse(widget.videoUrl);
      Logger.d('VIDEO_PLAYER', '解析后的URI: $videoUri');
      Logger.d('VIDEO_PLAYER',
          'URI scheme: ${videoUri.scheme}, host: ${videoUri.host}, port: ${videoUri.port}');

      // 验证URI是否有效
      if (videoUri.host.isEmpty) {
        throw Exception('视频URL格式错误：缺少host');
      }

      // 创建视频播放器控制器
      // video_player 2.8.2版本支持httpHeaders参数
      _controller = VideoPlayerController.networkUrl(
        videoUri,
        httpHeaders: {
          'User-Agent': 'MatrixApp/1.0',
          'Accept': 'video/mp4, video/*, */*',
        },
      );

      Logger.d('VIDEO_PLAYER', '视频播放器控制器已创建');

      // 设置视频播放配置
      _controller!.setLooping(false);
      _controller!.setVolume(1.0);

      // 监听视频初始化完成
      _controller!.addListener(() {
        if (!mounted) return;

        if (_controller!.value.isInitialized && !_isInitialized) {
          setState(() {
            _isInitialized = true;
            _isLoading = false;
          });
          Logger.d(
              'VIDEO_PLAYER', '视频初始化成功 - 时长: ${_controller!.value.duration}');
        }

        // 监听播放错误
        if (_controller!.value.hasError) {
          setState(() {
            _hasError = true;
            _isLoading = false;
            _errorMessage = _controller!.value.errorDescription ?? '视频加载失败';
          });
          Logger.e('VIDEO_PLAYER', '视频加载错误: $_errorMessage');
          Logger.e(
              'VIDEO_PLAYER', '错误详情: ${_controller!.value.errorDescription}');
        }
      });

      // 初始化视频（设置超时时间）
      Logger.d('VIDEO_PLAYER', '开始初始化视频...');
      await _controller!.initialize().timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          Logger.e('VIDEO_PLAYER', '视频初始化超时');
          throw Exception('视频加载超时，请检查网络连接或视频URL');
        },
      );

      Logger.d('VIDEO_PLAYER', '视频初始化完成，准备播放');

      // 自动播放
      await _controller!.play();
      Logger.d('VIDEO_PLAYER', '视频开始播放');
    } catch (e) {
      Logger.e('VIDEO_PLAYER', '视频初始化异常: $e');
      Logger.e('VIDEO_PLAYER', '异常类型: ${e.runtimeType}');
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
          _errorMessage = e.toString();
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  /// 自动隐藏控制栏
  void _startAutoHideControls() {
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        setState(() {
          _showControls = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 视频播放区域
          _buildVideoPlayer(),

          // 控制栏
          if (_showControls) _buildVideoControls(),

          // 顶部信息栏
          if (_showControls) _buildTopBar(),

          // 底部信息栏
          if (_showControls) _buildBottomInfo(),
        ],
      ),
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    return GestureDetector(
      onTap: _toggleControls,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.black,
        child: Stack(
          children: [
            // 视频播放器
            if (_controller != null && _isInitialized)
              Center(
                child: AspectRatio(
                  aspectRatio: _controller!.value.aspectRatio,
                  child: VideoPlayer(_controller!),
                ),
              )
            else if (_hasError)
              // 错误提示
              Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.error_outline,
                      color: Colors.white,
                      size: 64,
                    ),
                    const SizedBox(height: 16),
                    Text(
                      _errorMessage ?? '视频加载失败',
                      style: const TextStyle(color: Colors.white, fontSize: 16),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 24),
                    ElevatedButton(
                      onPressed: () {
                        setState(() {
                          _hasError = false;
                          _isLoading = true;
                          _isInitialized = false;
                        });
                        _initializeVideo();
                      },
                      child: const Text('重试'),
                    ),
                  ],
                ),
              )
            else
              // 加载中或显示封面
              Center(
                child: Stack(
                  children: [
                    // 视频封面
                    if (widget.post.coverUrl != null &&
                        widget.post.coverUrl!.isNotEmpty)
                      Image.network(
                        widget.post.coverUrl!,
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[900],
                            child: const Icon(
                              Icons.play_circle_outline,
                              color: Colors.white,
                              size: 80,
                            ),
                          );
                        },
                      )
                    else
                      Container(
                        color: Colors.grey[900],
                        child: const Icon(
                          Icons.play_circle_outline,
                          color: Colors.white,
                          size: 80,
                        ),
                      ),

                    // 加载指示器
                    if (_isLoading)
                      const Center(
                        child: CircularProgressIndicator(
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建视频控制栏
  Widget _buildVideoControls() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.transparent,
              Colors.black.withOpacity(0.8),
            ],
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 进度条
            _buildProgressBar(),
            const SizedBox(height: 12),

            // 控制按钮
            Row(
              children: [
                // 播放/暂停按钮
                GestureDetector(
                  onTap: _togglePlayPause,
                  child: Icon(
                    (_controller != null &&
                            _isInitialized &&
                            _controller!.value.isPlaying)
                        ? Icons.pause
                        : Icons.play_arrow,
                    color: Colors.white,
                    size: 32,
                  ),
                ),
                const SizedBox(width: 16),

                // 时间显示
                if (_controller != null && _isInitialized)
                  Text(
                    '${_formatDuration(_controller!.value.position)} / ${_formatDuration(_controller!.value.duration)}',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )
                else
                  const Text(
                    '00:00 / 00:00',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),

                const Spacer(),

                // 全屏按钮
                GestureDetector(
                  onTap: _toggleFullscreen,
                  child: const Icon(
                    Icons.fullscreen,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    if (_controller == null || !_isInitialized) {
      return const SizedBox.shrink();
    }

    final position = _controller!.value.position;
    final duration = _controller!.value.duration;
    final progress = duration.inMilliseconds > 0
        ? position.inMilliseconds / duration.inMilliseconds
        : 0.0;

    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        activeTrackColor: Colors.white,
        inactiveTrackColor: Colors.white.withOpacity(0.3),
        thumbColor: Colors.white,
        overlayColor: Colors.white.withOpacity(0.2),
        thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
        trackHeight: 3,
      ),
      child: Slider(
        value: progress.clamp(0.0, 1.0),
        onChanged: (value) {
          if (_controller != null && _isInitialized) {
            final newPosition = Duration(
              milliseconds: (duration.inMilliseconds * value).round(),
            );
            _controller!.seekTo(newPosition);
            setState(() {});
          }
        },
      ),
    );
  }

  /// 构建顶部信息栏
  Widget _buildTopBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.black.withOpacity(0.8),
                Colors.transparent,
              ],
            ),
          ),
          child: Row(
            children: [
              // 返回按钮
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child: const Icon(
                  Icons.arrow_back,
                  color: Colors.white,
                  size: 24,
                ),
              ),
              const SizedBox(width: 16),

              // 视频标题
              Expanded(
                child: Text(
                  widget.videoTitle ?? widget.post.content,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              // 更多按钮
              GestureDetector(
                onTap: _showMoreOptions,
                child: const Icon(
                  Icons.more_vert,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建底部信息
  Widget _buildBottomInfo() {
    return Positioned(
      bottom: 120,
      left: 16,
      right: 16,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.6),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 作者信息
            Row(
              children: [
                CircleAvatar(
                  radius: 20,
                  backgroundColor: Colors.grey[700],
                  backgroundImage: widget.post.userAvatar != null && widget.post.userAvatar!.isNotEmpty
                      ? NetworkImage(widget.post.userAvatar!)
                      : null,
                  child: widget.post.userAvatar == null || widget.post.userAvatar!.isEmpty
                      ? const Icon(Icons.person, size: 24, color: Colors.white)
                      : null,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.post.username,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        '${widget.post.viewsCount} 次观看',
                        style: TextStyle(
                          color: Colors.white.withOpacity(0.8),
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
                ElevatedButton(
                  onPressed: _handleFollow,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                  ),
                  child: const Text('关注'),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // 视频描述
            Text(
              widget.post.summary ?? widget.post.content,
              style: TextStyle(
                color: Colors.white.withOpacity(0.9),
                fontSize: 14,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 12),

            // 互动按钮
            Row(
              children: [
                _buildActionButton(
                  icon: widget.post.isLiked
                      ? Icons.favorite
                      : Icons.favorite_border,
                  label: '${widget.post.likesCount}',
                  color: widget.post.isLiked ? Colors.red : Colors.white,
                  onTap: () => _handleLike(),
                ),
                const SizedBox(width: 24),
                _buildActionButton(
                  icon: Icons.comment,
                  label: '${widget.post.commentsCount}',
                  color: Colors.white,
                  onTap: _handleComment,
                ),
                const SizedBox(width: 24),
                _buildActionButton(
                  icon: Icons.share,
                  label: '${widget.post.sharesCount}',
                  color: Colors.white,
                  onTap: _handleShare,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 切换控制栏显示
  void _toggleControls() {
    setState(() {
      _showControls = !_showControls;
    });

    if (_showControls) {
      _startAutoHideControls();
    }
  }

  /// 切换播放/暂停
  Future<void> _togglePlayPause() async {
    if (_controller == null || !_isInitialized) return;

    if (_controller!.value.isPlaying) {
      await _controller!.pause();
    } else {
      await _controller!.play();
    }

    setState(() {});
    _startAutoHideControls();
  }

  /// 切换全屏
  void _toggleFullscreen() {
    // TODO: 实现全屏功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('全屏功能开发中...')),
    );
  }

  /// 处理点赞
  void _handleLike() async {
    try {
      await ApiService().likePost(widget.post.id, !widget.post.isLiked);

      setState(() {
        // 更新点赞状态
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!widget.post.isLiked ? '已点赞' : '已取消点赞'),
        ),
      );
    } catch (e) {
      Logger.e('VIDEO_PLAYER', '点赞失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理评论
  void _handleComment() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 8),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),

            // 标题
            const Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '评论',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),

            // 评论列表
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: 10, // 模拟评论数量
                itemBuilder: (context, index) {
                  return _buildCommentItem(
                    '用户${index + 1}',
                    '这是第${index + 1}条评论，视频内容很不错！',
                    '${index + 1}小时前',
                  );
                },
              ),
            ),

            // 评论输入框
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                border: Border(
                  top: BorderSide(color: Colors.grey[200]!),
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      decoration: const InputDecoration(
                        hintText: '写下你的评论...',
                        border: OutlineInputBorder(),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 8,
                        ),
                      ),
                      maxLines: null,
                    ),
                  ),
                  const SizedBox(width: 8),
                  IconButton(
                    onPressed: () {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('评论成功')),
                      );
                    },
                    icon: const Icon(Icons.send),
                    style: IconButton.styleFrom(
                      backgroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建评论项
  Widget _buildCommentItem(String username, String content, String time) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 16,
            backgroundColor: Colors.grey[300],
            child: Text(
              username[0],
              style: const TextStyle(fontSize: 12),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      username,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      time,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 4),
                Text(
                  content,
                  style: const TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 处理分享
  void _handleShare() async {
    try {
      await ApiService().sharePost(widget.post.id);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('分享成功')),
      );
    } catch (e) {
      Logger.e('VIDEO_PLAYER', '分享失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('分享失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理关注
  void _handleFollow() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('关注功能开发中...')),
    );
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.download),
              title: const Text('下载视频'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('下载功能开发中...')),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.bookmark_border),
              title: const Text('收藏'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('收藏功能开发中...')),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.report),
              title: const Text('举报'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('举报功能开发中...')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化时长
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = twoDigits(duration.inHours);
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));

    if (duration.inHours > 0) {
      return '$hours:$minutes:$seconds';
    } else {
      return '$minutes:$seconds';
    }
  }
}
